import 'package:base_lib/common/base/base_bloc_page.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/parameters.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:doctor_examine_lib/doctor_examine_componet.dart';
import 'package:doctor_examine_lib/hospital_list/hospital_list_bloc.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HospitalListPage
    extends BaseBlocPage<HospitalListBloc, _HospitalListState> {
  HospitalListPage(Parameters parameters) : super(parameters);

  @override
  _HospitalListState generateThemeState() {
    return _HospitalListState();
  }
}

class _HospitalListState extends BaseBlocPageState<HospitalListBloc> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  void initState() {
    super.initState();
  }

  @override
  ignoreWindowWidget() => false;

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return Scaffold(
      appBar: AppBar(
        title: Text("选择检查医院"),
        actions: [
          FlatButton(
            child: Text(
              "确定",
              style: TextStyle(color: Colors.white),
            ),
            onPressed: () {
              bloc.confirmSelectedHospital(context);
            },
          )
        ],
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: StreamBuilder(
          stream: bloc.dataSourceSubject,
          initialData: [],
          builder: (context, snapshot) {
            return snapshot.hasData
                ? SmartRefresher(
                    enablePullDown: true,
                    enablePullUp: false,
                    header: WaterDropHeader(),
                    controller: _refreshController,
                    onRefresh: _onRefresh,
                    child: _cellBuilder(snapshot.data, bloc),
                  )
                : Container();
          },
        ),
      ),
    );
  }

  void _onRefresh() async {
    print('object----------11');
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    bloc.fetchHospitalDoctors(() {
      _refreshController.refreshCompleted();
    }, () {
      _refreshController.refreshFailed();
    });
  }

  Widget _cellBuilder(list, bloc) {
    return ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              bloc.selectedItem(index);
            },
            child: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      _avatarBuilder(list[index]),
                      _contentBuilder(list[index])
                    ],
                  ),
                  _radioBuilder(index)
                ],
              ),
            ),
          );
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 10,
            thickness: 10,
            color: ColorUtil.color("#f6f6f6"),
          );
        },
        itemCount: list.length);
  }

  Widget _radioBuilder(index) {
    return StreamBuilder(
        stream: bloc.selectedIndexSubject,
        initialData: 0,
        builder: (context, snapshot) {
          return Radio(
              value: index,
              groupValue: snapshot.data,
              onChanged: (value) {
                bloc.selectedItem(value);
              });
        });
  }

  Widget _avatarBuilder(item) {
    return Padding(
      padding: const EdgeInsets.all(12.0),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(6),
        child: ObjectUtil.isEmpty(item.photoUrl)
            ? Image.asset(
                "images/public/public_avatar.png",
                package: DoctorExamineComponent.assetsPackageName,
                height: 76,
                width: 76,
              )
            : Image.network(
                item.photoUrl,
                width: 76,
                height: 76,
                fit: BoxFit.cover,
              ),
      ),
    );
  }

  Widget _contentBuilder(item) {
    return Padding(
      padding: EdgeInsets.only(top: 12.0, bottom: 12.0, right: 12.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _contentTopBuilder(item),
          _contentMiddleBuilder(item),
          _contentBottomBuilder(item)
        ],
      ),
    );
  }

  Widget _contentTopBuilder(item) {
    return Row(
      children: [
        Text(
          returnOrgName(item),
          style: TextStyle(fontSize: 18),
          textAlign: TextAlign.left,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 8),
          child: ObjectUtil.isNotEmpty(getName(item))
              ? Container(
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.red, width: 1)),
                  child: Padding(
                    padding: const EdgeInsets.only(left: 4.0, right: 4.0),
                    child: Text(getName(item),
                        style: TextStyle(fontSize: 15, color: Colors.red)),
                  ),
                )
              : Container(),
        )
      ],
    );
  }

  Widget _contentMiddleBuilder(item) {
    return Padding(
      padding: const EdgeInsets.only(top: 6.0),
      child: Row(
        children: [
          Text(
            item.hospitalGrade,
            style: TextStyle(fontSize: 16, color: Colors.red),
          ),
          Padding(
            padding: EdgeInsets.only(left: 12.0),
            child: Text(
              item.natureName,
              style: TextStyle(fontSize: 16, color: ColorUtil.color("#999999")),
            ),
          )
        ],
      ),
    );
  }

  Widget _contentBottomBuilder(item) {
    return Padding(
      padding: const EdgeInsets.only(top: 6.0),
      child: Row(
        children: [
          Image.asset(
            "images/public/public_location.png",
            package: DoctorExamineComponent.assetsPackageName,
            height: 15.0,
            width: 15.0,
          ),
          Padding(
            padding: EdgeInsets.only(left: 12.0),
            child: Text(
              getDistance(item.distance),
              style: TextStyle(fontSize: 16, color: ColorUtil.color("#999999")),
            ),
          )
        ],
      ),
    );
  }

  String getName(item) {
    if (item.ownHospitalCode == 1) {
      return "我的医院";
    }
    if (item.practiceCode == 1) {
      return "我的执业医院";
    }
    return "";
  }

  String returnOrgName(item) {
    if (item.ownHospitalCode == 1) {
      return item.orgName.length > 10
          ? item.orgName.substring(0, 9) + "..."
          : item.orgName;
    }
    if (item.practiceCode == 1) {
      return item.orgName.length > 9
          ? item.orgName.substring(0, 8) + "..."
          : item.orgName;
    }
    return item.orgName.length > 15
        ? item.orgName.substring(0, 14) + "..."
        : item.orgName;
  }

  String getDistance(distance) {
    return distance > 1000
        ? "距离患者${(distance / 1000).toStringAsFixed(2)}km"
        : "距离患者${distance}m";
  }

  @override
  HospitalListBloc generateBloc() {
    return HospitalListBloc();
  }
}
